package com.sky.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sky.constant.StatusConstant;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.entity.Category;
import com.sky.result.Result;
import com.sky.service.ICategoryService;
import io.swagger.models.auth.In;
import org.apache.coyote.http11.upgrade.UpgradeServletOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.AccessType;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/admin/category")
public class CategoryController {
    @Autowired
    private ICategoryService iCategoryService;

    @GetMapping("/list")
    public Result getList(Category category){
        LambdaQueryWrapper<Category> lqw =new LambdaQueryWrapper<>();
        lqw.eq(category.getType()!=null,Category::getType,category.getType());
        List<Category> list = iCategoryService.list(lqw);
        return Result.success(list);
    }

    @GetMapping("/page")
    public Result page (CategoryPageQueryDTO categoryPageQueryDTO){
        LambdaQueryWrapper<Category> lqw =new LambdaQueryWrapper<>();
        lqw.like(categoryPageQueryDTO.getName()!=null&&!categoryPageQueryDTO.getName().trim().isEmpty(),
                Category::getName,categoryPageQueryDTO.getName());
        lqw.eq(categoryPageQueryDTO.getType()!=null,Category::getType,categoryPageQueryDTO.getType());
        IPage<Category> iPage =new Page<>(categoryPageQueryDTO.getPage(),categoryPageQueryDTO.getPageSize());
        lqw.orderByDesc(Category::getSort);
        iCategoryService.page(iPage,lqw);
        return Result.success(iPage);
    }

    @PostMapping
    public Result add (@RequestBody Category category){
        category.setStatus(StatusConstant.ENABLE);
        iCategoryService.save(category);
        return Result.success();
    }

    @PutMapping
    public Result update(@RequestBody Category category ){
        iCategoryService.updateById(category);
        return Result.success();
    }

    @DeleteMapping
    public Result delete(Long id){
        iCategoryService.removeById(id);
        return Result.success();
    }

    @PostMapping("/status/{status}")
    public Result status(@PathVariable Integer status,Long id){
        LambdaUpdateWrapper<Category> luw =new LambdaUpdateWrapper<>();
        luw.eq(Category::getId ,id).set(Category::getStatus ,status);
        iCategoryService.update(luw);
        return Result.success();
    }
}
